<template>
  <view class="main-box">
    <eui-background type="full">
      <view class="top-view">
        <view class="status-view">
          <Status :status="onlineStatus" :onlineTime="onlineTime" @clickFunc="clickFunc" @clickClose="closeMoreModal" />
        </view>
        <view class="nva-bar">{{ title }}</view>
        <view class="menu-view">
          <view @click="myCenter">
            <eui-uicons size='36' fontFamily="enjoyIcon5" customPrefix="icon-wodedongtai" color="#ffffff" />
          </view>
          <view style="margin-left:36rpx" @click="addTask">
            <eui-uicons size='36' fontFamily="enjoyIcon5" customPrefix="icon-zengjia" color="#ffffff" />
          </view>
        </view>
      </view>
      <TaskTab :tabs="tabData" :value="industryTabIndex" :spaceLeft="spaceLeft" :tabStyle="tabStyle"
               @change="tabChange" @iconClick="iconClick">
      </TaskTab>
      <!-- <eui-tab :tabs="tabData" :value="industryTabIndex" :spaceLeft="spaceLeft" showBadge @change="tabChange"
        :tabStyle="tabStyle" themeColor="rgba(255, 255, 255, 1)"></eui-tab>

       -->
      <view class="main-view" :style="{ height: scrollHeight + 'px' }">
        <TaskList v-if="onlineStatus && curTaskList.length > 0" :taskList="curTaskList" refresher="true" :industryTabIndex="industryTabIndex"
                  @ItemClick="itemClick" @leftItemClick="listItemClick" @buttonClick="listItemClick" @onRefresh="getData" :refresher="true"></TaskList>
        <view v-else-if="onlineStatus" class="white-view">
          <!--任务为空-->
          <image src="@/static/img/no_data.png" mode="scaleToFill"
                 style="width: 300rpx; height: 300rpx; margin-top: 100rpx;" />
          <text class="tips-level2">{{ industryTabIndex === 0 ? '还没有任务，请耐心等待' : industryTabIndex === 1 ? '暂无转交申请任务' : '你还没有任务，去抢一个试试' }}</text>
        </view>
        <view v-else class="white-view">
          <!--下线-->
          <image src="@/static/img/rdsImgs/quest_downline.png" mode="scaleToFill"
                 style="width: 300rpx; height: 300rpx; margin-top: 100rpx;" />
          <text class="tips-level1">您当前处于下线状态</text>
          <text class="tips-level2">下线时将不再接到新任务提示!</text>
          <eui-button type="base" title="立即上线" singleTag="online" @buttonClick="changeToOnline" />
        </view>
        <view v-if="showFilter" class="popup-content">
          <view class="popup-top">
            <Filter v-if="typeTempList.length > 0" :range="typeTempList" v-model="typeTempValue" title="工单筛选 (可多选)" />
            <Filter :range="levelTempList" v-model="levelTempValue" title="任务等级 (可多选)" />
            <Filter :range="dateList" v-model="dateTempValue" title="日期范围" :isMulti="false" />
            <view class="btn-view">
              <eui-button type="max2" title="重置" singleTag="reset" maxWidth="332"
                          @buttonClick="confirm"></eui-button>
              <eui-button type="max" title="确定" singleTag="fix" maxWidth="332"
                          @buttonClick="confirm"></eui-button>
            </view>
          </view>
          <view class="popup-mask" @click="hideFilter" />
        </view>
        <view v-show="showAddTask" class="popup-content">
          <view class="popup-top">
            <DropAddTask :menuList="menuList" @menuItemClick="addTaskItemClick"
                         @moreMenuClick="moreTaskItemClick"></DropAddTask>
          </view>
          <view class="popup-mask" @click="hideAddTask" />
        </view>
      </view>
      <eui-popup ref="popupAdjust" background-color="#f8f8f8" type="center" :mask-click="true" :animation="false">
        <view class="popup-adjust">
          <TaskAdjust :formatData="formatData" @hidePopup="hideAdjustPopup"
                      @clickFunc="judgeAdjust" @userFunc="choosePerson"
                      :title="formatData.title" :btnTitle="formatData.btnTitle" />
        </view>
      </eui-popup>
      <eui-popup ref="popupDelay" background-color="#f8f8f8" type="center" :mask-click="true" :animation="false">
        <view class="popup-delay" :style="{height: taskMode === '5' ? '990rpx' : '902rpx' }">
          <TaskDelay :taskId="getTaskId(currentItem.item)" :taskMode="taskMode" @hidePopup="hideDelayPopup"
                     @closePopup="closeDelayPopupp" />
        </view>
      </eui-popup>
      <CustomTabBar current="任务" />
    </eui-background>
  </view>
</template>

<script setup type="ts">
import CustomTabBar from '@/components/CustomTabBar.vue';
import TaskList from '../../RdsViews/TaskWork/components/taskList.vue'
import Status from '../../RdsViews/TaskWork/components/status.vue'
import TaskTab from '../../RdsViews/TaskWork/components/taskTab.vue'
import Filter from '../../RdsViews/TaskWork/components/filter.vue';
import DropAddTask from '../../RdsViews/TaskWork/components/dropAddTask.vue'
import TaskAdjust from '../../RdsViews/TaskWork/components/taskAdjust.vue'
import TaskDelay from '../../RdsViews/TaskWork/components/taskDelay.vue'
import { ref, onMounted } from 'vue'
import service from "@/common/service";
import { getRdsUrl, rdsRequest } from '@/hooks/rdsServices';
import {useMainStore} from "@/store/modules/store";
import {useLoginStore} from "@/store/modules/useLoginStore";
import {onLoad, onShow} from "@dcloudio/uni-app";
import {init} from "@/hooks/init";
import { getRelatedName, getDictName, getDictSelectList, getDictList } from '../../RdsViews/components/RelatedName.js';
import useService from '@/hooks/useService';
import dayjs from 'dayjs';
import Guid from "@/common/guid";
const mainService = useService({ prefix: "mainApi" });
const mainStore = useMainStore();
const { loginInfo } = mainStore;
const LoginStore = useLoginStore();
const rdsUrl = getRdsUrl();
const title = ref('任务');
const sUserStore = ref('');
const sUserStoreName = ref('');
const sUser = ref('');
const searchText = ref('');
// 在线状态
const onlineStatus = ref(false);
const onlineTime = ref('');
const msg = ref('您已经上线8个小时，剩余工单0个！');
const menuList = ref([]);
const onlineGuid = ref(''); // 上线的c_guid
// 筛选框
// 任务类型
const typeList = ref([]);
const typeTempList = ref([]);
const typeValue = ref('');
const typeTempValue = ref('');
// 等级
const levelList = ref([]);
const levelTempList = ref([]);
const levelValue = ref('');
const levelTempValue = ref('');
// 目标角色
const roleList = ref([]);
const roleValue = ref('');
const roleTempValue = ref('');
// 状态
// 1:正常;2:临期;3:延期;4:超期
const statusList = ref([
  {text: '正常', value: '1'},
  {text: '临期', value: '2'},
  {text: '延期', value: '3'},
  {text: '超期', value: '4'},
]);
const statusValue = ref('');
const statusTempValue = ref('');
// 日期范围
const dateList = ref([
  {text: '近七天', value: '1'},
  {text: '近三天', value: '2'},
  {text: '今天', value: '3'},
  {text: '明天', value: '4'},
  {text: '未来三天', value: '5'},
  {text: '未来七天', value: '6'},
]);
const dateValue = ref('');
const dateTempValue = ref('');
const showFilter = ref(false); // 筛选弹框
const showAddTask = ref(false);  //下拉新增任务
// 列表数据
const curTaskList = ref([]); // 当前展示的列表
const newTaskList = ref([]); // 新任务
const yjdTaskList = ref([]); // 已接单
const dealTaskList = ref([]); // 处理中
const deliverTaskList = ref([]); //转交申请任务
const dataList = ref([]); // 任务类型定义
const CurrentPage = ref(1);  //第几页
const PageSize = ref(100);  //每页100条
const RowsCount = ref(0);  //总条数
const PageCount = ref(1);  //总页数
// 弹框
const popupAdjust = ref(null);
const popupDelay = ref(null);
const taskMode = ref('1');
// 指派
const formatData = ref({
  title: '', // 标题
  btnTitle: '', // 按钮
  personName: '', // 处理人
  personId: '',
  costTime: 30, // 预估时间
  startTime: '', // 开始时间
  endTime: '', // 结束时间
})
const currentItem = ref({}); // 当前选中的任务


const industryTabIndex = ref(0);
const spaceLeft = ref(0);
const tabStyle = ref({ justifyContent: 'flex-start'});
const tabData = ref([
  { name:'新任务',icon:'icon-shaixuan2'},
  { name:'转交申请任务',icon:'' },
  { name:'已接单',icon:''},
  { name:'处理中',icon:'' },
]);

const tabChange = async(data)=>{
  closeAllPopup();
  if (industryTabIndex.value === data) return;
  industryTabIndex.value = data;
  if (industryTabIndex.value == 0) {
    curTaskList.value = newTaskList.value;
  } else if (industryTabIndex.value == 1) {
    curTaskList.value = deliverTaskList.value;
  } else if (industryTabIndex.value == 2) {
    curTaskList.value = yjdTaskList.value;
  } else if (industryTabIndex.value == 3) {
    curTaskList.value = dealTaskList.value;
  }
  await getData();
}
// 我的动态
const myCenter = () => {
  closeAllPopup();
  closeMoreModal();
  uni.navigateTo({
    url: `../../RdsViews/TaskWork/center/myCenter`
  });
}
const addTask = ()=>{
  showAddTask.value=true;
  showFilter.value = false;
  closeMoreModal();
}
const hideAddTask = () =>{
  showAddTask.value=false;
}
const scrollHeight = ref(0);
// 初始化滚动区域高度
const initScrollView =() => {
  uni.getSystemInfo({
    success: (res) => {
      const query = uni.createSelectorQuery().in(this);
      query.select('.main-view').boundingClientRect(data => {
        scrollHeight.value = (res.windowHeight - (data?.top??0) - 59);
      }).exec();
    }
  })
}

const setDefault = async () => {
  sUserStore.value = loginInfo.sUserStore;
  sUserStoreName.value = loginInfo.sUserStoreName;
  sUser.value = loginInfo.sUser;
}

// 获取系统参数、字典
const getSysConfig = async () => {
  const list = await getDictList("任务角色等级");
  list.forEach(e => {
    levelList.value.push({
      text: e.c_name,
      value: e.c_id,
      checked: false,
    });
  });
}

// 获取目标角色
const getUserRole = async () => {
  const result = await rdsRequest(rdsUrl.mainApi, 'taskdefine', 'FetchTaskRoles', '');
  if (result && result.length > 0) {
    roleList.value = result.map(item => ({
      text: item.Name,
      value: item.Code,
    }));
  }
}

onMounted(() => {
  initScrollView();
});

onLoad(async () => {
  service.enjoyShowLoading('正在加载...');
  await init();
  // await getUserRole();
  await getSysConfig();
  await setDefault();
  await searchOnlineStatus();
  service.enjoyHideLoading();
})

onShow(async () => {
  service.enjoyShowLoading('正在加载...');
  await getTaskDefine();
  await getData();
  service.enjoyHideLoading();
})

// 获取数据
const getData = async () => {
  if (industryTabIndex.value == 0){
    await getTaskAllot();
  } else if (industryTabIndex.value == 1) {
    await getDeliverTaskList();
  } else {
    showFilter.value = false;
    await getToDoTasks();
  }
}

// 任务分配
const getTaskAllot = async (e) => {
  if (!onlineStatus.value) return;
  service.enjoyShowLoading('正在加载...');
  let req = {};
  if (roleValue.value) {
    req.c_task_role = roleValue.value;
  }
  if (statusValue.value) {
    req.c_task_status = statusValue.value;
  }
  const result = await rdsRequest(rdsUrl.mainApi, 'taskallot', 'FetchTaskAllot', req);
  // 根据筛选条件过滤显示
  let list = JSON.parse(JSON.stringify(result));
  // 筛选任务类型
  if (typeValue.value) {
    let typeRangeList = typeValue.value.split(',');
    list = list.filter(item => typeRangeList.includes(item.c_class_code));
  }
  // 筛选等级
  if (levelValue.value) {
    let levelRangeList = levelValue.value.split(',');
    list = list.filter(item => levelRangeList.includes(item.c_level));
  }
  // 筛选日期
  if (dateValue.value) {
    // 获取今天的日期
    const today = new Date();
    today.setHours(0, 0, 0, 0); // 只保留日期部分
    // 定义筛选的日期范围
    let startDate, endDate;
    switch (dateValue.value) {
      case '1': // 近七天
        startDate = new Date(today);
        startDate.setDate(today.getDate() - 6);
        endDate = today;
        break;
      case '2': // 近三天
        startDate = new Date(today);
        startDate.setDate(today.getDate() - 2);
        endDate = today;
        break;
      case '3': // 今天
        startDate = today;
        endDate = today;
        break;
      case '4': // 明天
        startDate = new Date(today);
        startDate.setDate(today.getDate() + 1);
        endDate = startDate;
        break;
      case '5': // 未来三天
        startDate = new Date(today);
        startDate.setDate(today.getDate() + 1);
        endDate = new Date(startDate);
        endDate.setDate(startDate.getDate() + 2);
        break;
      case '6': // 未来七天
        startDate = new Date(today);
        startDate.setDate(today.getDate() + 1);
        endDate = new Date(startDate);
        endDate.setDate(startDate.getDate() + 6);
        break;
    }
    // 筛选符合条件的任务单
    list = list.filter(task => {
      const taskDate = new Date(task.c_plan_begin_time);
      taskDate.setHours(0, 0, 0, 0);
      return taskDate >= startDate && taskDate <= endDate;
    });
  }
  list = list.map(x=>{
    return{
      ...x,
      showMore:false
    }
  })
  newTaskList.value = list;
  curTaskList.value = list;
  service.enjoyHideLoading();
}

// 待办任务
const getToDoTasks = async (e) => {
  if (!onlineStatus.value) return;
  service.enjoyShowLoading('正在加载...');
  const result = await rdsRequest(rdsUrl.mainApi, 'tasktodo', 'FetchToDoTasks', {});
  if (result && result.length > 0) {
    //TODO   这里先写死成登录人   后面接口改
    let resultTemp = result.map(x=>{
      return{
        ...x,
        c_recv_userno:loginInfo.sUser,
        showMore:false
      }
    })
    // 已接单
    yjdTaskList.value = resultTemp.filter(item => item.c_progress === 0);
    // 处理中
    dealTaskList.value = resultTemp.filter(item => item.c_progress > 0 && item.c_progress < 100);
    if (industryTabIndex.value == 2) {
      curTaskList.value = yjdTaskList.value;
    } else if (industryTabIndex.value == 3) {
      curTaskList.value = dealTaskList.value;
    }
  } else {
    curTaskList.value = [];
    yjdTaskList.value = [];
    dealTaskList.value = [];
  }
  service.enjoyHideLoading();
}

// 转交申请任务
const getDeliverTaskList = async (e) => {
  if (!onlineStatus.value) return;
  service.enjoyShowLoading('正在加载...');
  const result = await rdsRequest(rdsUrl.mainApi, 'taskdelivertodo', 'FetchDeliverToDoTasks', {});
  if (result && result.length > 0) {
    let list = JSON.parse(JSON.stringify(result));
    list = list.map(x=>{
      return{
        ...x,
        showMore:false
      }
    })
    curTaskList.value = list;
    deliverTaskList.value = list;
  } else {
    curTaskList.value = [];
    deliverTaskList.value = [];
  }
  service.enjoyHideLoading();
}

// 获取任务类型定义
const getTaskDefine = async () => {
  service.enjoyShowLoading('正在加载...');
  const req = {
    IsNotPage: true,
    CurrentPage: 1,
    PageSize: 100,
    WhereList: []
  }
  const iconList = ['icon-shengxianlihuo','icon-feishengxianlihuo','icon-dingdanjianhuo']
  const result = await rdsRequest(rdsUrl.mainApi, 'taskdefine', 'EnjoyQueryList', req);
  if(result){
    let index=0;
    menuList.value = result.ReturnObject.map(x=>{
      index++
      return {
        c_menu_code:x.c_class_code,
        c_menu_title:x.c_name,
        c_menu_comenu_content:x.c_name,
        c_menu_icon: index>iconList.length?iconList[2]:iconList[index-1]
      }
    })
    // 筛选框数据
    typeList.value = result.ReturnObject
        .filter(item => item.c_class_code)
        .map(item => {
          return {
            text: item.c_name,
            value: item.c_class_code,
            checked: false,
          }
        })
  }
  service.enjoyHideLoading();
}

const clickFunc = () => {
  if (onlineStatus.value) {
    // 当前在线的处理
    changeToOffline()
  } else {
    // 当前离线的处理
    changeToOnline()
  }
}

// 查询在线状态
const searchOnlineStatus = async () => {
  uni.showLoading({ title: "查询中...", mask: true });
  let req = {
    currentUserNo: loginInfo.sUser,
    storeId: loginInfo.sUserStore,
    guid: onlineGuid.value,
  }
  const res = await mainService.request('tasktodo', 'FindInWorkingItem', req);
  if (res) {
    onlineStatus.value = true;
    onlineTime.value = res.c_begin_work_dt; // 记录上线时间
    onlineGuid.value = res.c_guid; // 记录上线guid
    await getData();
  }
}

// 上线
const changeToOnline = async () => {
  // 调用上线服务前查询上线状态, 已上线则直接更新状态, 未上线则调用上线服务
  uni.showLoading({ title: "上线中...", mask: true });
  let searchReq = {
    currentUserNo: loginInfo.sUser,
    storeId: loginInfo.sUserStore,
    guid: onlineGuid.value,
  }
  const searchRes = await mainService.request('tasktodo', 'FindInWorkingItem', searchReq);
  if (searchRes) {
    uni.hideLoading();
    // 已上线
    onlineStatus.value = true;
    onlineTime.value = searchRes.c_begin_work_dt; // 记录上线时间
    onlineGuid.value = searchRes.c_guid; // 记录上线guid
    await getData();
  } else {
    // 未上线
    let req = {
      currentUserNo: loginInfo.sUser,
      storeId: loginInfo.sUserStore,
    }
    const res = await mainService.request('tasktodo', 'BeginReceiveTask', req);
    uni.hideLoading();
    if (res && res.c_is_inworking === '1') {
      onlineStatus.value = true;
      onlineTime.value = res.c_begin_work_dt; // 记录上线时间
      onlineGuid.value = res.c_guid; // 记录上线guid
      await getData();
    }
  }
}

// 下线
const changeToOffline = async () => {
  uni.showLoading({ title: "下线中...", mask: true });
  const res = await mainService.request('tasktodo', 'EndReceiveTask', onlineGuid.value);
  uni.hideLoading();
  onlineStatus.value = false;
  curTaskList.value = [];
  newTaskList.value = [];
  yjdTaskList.value = [];
  dealTaskList.value = [];
  deliverTaskList.value = [];
}

// 关闭筛选框
const hideFilter = () => {
  showFilter.value = false;
}

// 按钮点击事件
const confirm = (e) => {
  let { singleTag } = e;
  switch (singleTag) {
    case 'reset':
      typeTempValue.value = '';
      levelTempValue.value = '';
      roleTempValue.value = '';
      statusTempValue.value = '';
      dateTempValue.value = '';
      typeTempList.value.forEach(item => item.value == '' ? item.checked = true : item.checked= false);
      levelTempList.value.forEach(item => item.value == '' ? item.checked = true : item.checked= false);
      break;
    case 'fix':
      typeValue.value = typeTempValue.value;
      levelValue.value = levelTempValue.value;
      roleValue.value = roleTempValue.value;
      statusValue.value = statusTempValue.value;
      typeList.value = typeTempList.value;
      levelList.value = levelTempList.value;
      dateValue.value = dateTempValue.value;
      hideFilter();
      getData();
      break;
  }
}

// 筛选
const iconClick = (e)=>{
  if (industryTabIndex.value !== 0) return;
  showFilter.value = !showFilter.value;
  showAddTask.value = false;
  closeMoreModal();
  typeTempValue.value = typeValue.value;
  levelTempValue.value = levelValue.value;
  typeTempList.value = JSON.parse(JSON.stringify(typeList.value));
  levelTempList.value = JSON.parse(JSON.stringify(levelList.value));
  roleTempValue.value = roleValue.value;
  statusTempValue.value = statusValue.value;
  dateTempValue.value = dateValue.value;
}

// 查看明细
const itemClick = (item)=>{
  closeMoreModal();
  let taskId = getTaskId(item);
  let userNo = getUserNo(item);
  let billId = item.c_bill_id ? item.c_bill_id : '';
  let billType = item.c_bill_type ? item.c_bill_type : '';
  uni.navigateTo({
    url: `../../RdsViews/TaskWork/taskDetail?TaskId=${taskId}&selectType=${industryTabIndex.value}&UserNo=${userNo}&BillId=${billId}&BillType=${billType}`
  });
}

// 获取taskId
const getTaskId = (item) => {
  let taskId = 0;
  if (industryTabIndex.value === 0) {
    taskId = item.c_code;
  } else {
    taskId = item.c_task_code;
  }
  return taskId;
}

// 获取userNo
const getUserNo = (item) => {
  let userNo = loginInfo.sUser;
  if (industryTabIndex.value === 1) {
    userNo = item.c_recv_userno;
  }
  return userNo;
}

// 列表点击事件
const listItemClick = async (data) => {
  let { type, item } = data;
  currentItem.value = data;
  switch (type) {
    case '指派':
      await showAdjustPopup(type, item);
      break;
    case '转单':
      await showAdjustPopup(type, item);
      break;
    case '抢单':
      await ReceiveTask();
      break;
    case '置顶':
      await TopTask();
      break;
    case '延时':
      if (item.hasOwnProperty('c_recv_userno') && item.c_recv_userno === loginInfo.sUser) {
        taskMode.value = "5";
      } else {
        taskMode.value = "1";
      }
      popupDelay.value.open('center');
      break;
    case '开始处理':
      CommitTaskBeginRecord(item);
      break;
    case '已完成':
      itemClick(item);
      break;
    case '领取转单':
      await agreeTask(item);
      break;
    case '驳回转单':
      await disagreeTask(item);
      break;
  }
}

//领取转单
const agreeTask = async (item) => {
  uni.showModal({
    title: ' 提示',
    content: '请您确认是否同意接收所选任务？',
    showCancel: true,
    success: async (res) => {
      if (res.confirm) {
        uni.showLoading({ title: "处理中...", mask: true });
        const req = [item.c_deliver_guid];
        const res = await mainService.request('taskdelivertodo', 'AgreeTaskDeliver', req);
        uni.hideLoading();
        if (res && res.length > 0) {
          if (res[0].Msg) {
            uni.showToast({
              duration: 2000,
              icon: 'none',
              title: res[0].Msg
            });
          } else {
            uni.showToast({
              duration: 2000,
              icon: 'none',
              title: '领取转交成功！'
            });
            setTimeout(async () => {
              getData()
            }, 1000)
          }
        } else {
          uni.showToast({
            duration: 2000,
            icon: 'none',
            title: '领取转交失败！'
          });
        }
      }
    }
  });
}

//驳回转单
const disagreeTask = async (item) => {
  uni.showModal({
    title: ' 提示',
    content: '请您确认是否驳回所选任务的转交？',
    showCancel: true,
    success: async (res) => {
      if (res.confirm) {
        uni.showLoading({ title: "处理中...", mask: true });
        const req = [item.c_deliver_guid];
        const res = await mainService.request('taskdelivertodo', 'RejectTaskDeliver', req);
        uni.hideLoading();
        if (res && res.length > 0) {
          if (res[0].Msg) {
            uni.showToast({
              duration: 2000,
              icon: 'none',
              title: res[0].Msg
            });
          } else {
            uni.showToast({
              duration: 2000,
              icon: 'none',
              title: '驳回转交成功！'
            });
            setTimeout(async () => {
              getData()
            }, 1000)
          }
        } else {
          uni.showToast({
            duration: 2000,
            icon: 'none',
            title: '驳回转交失败！'
          });
        }
      }
    }
  });
}

// 延时
const hideDelayPopup = async () => {
  getData()
}

const closeDelayPopupp = async () => {
  popupDelay.value.close();
}

//抢单
const ReceiveTask = async () => {
  uni.showLoading({ title: "处理中...", mask: true });
  let taskId = getTaskId(currentItem.value.item);
  const req = [taskId];
  const res = await mainService.request('taskallot', 'ReceiveTask', req);
  uni.hideLoading();
  if (res && res.length > 0) {
    if (res[0].ErrorMsg) {
      uni.showToast({
        duration: 2000,
        icon: 'none',
        title: res[0].ErrorMsg
      });
    } else {
      uni.showToast({
        duration: 2000,
        icon: 'none',
        title: '抢单成功'
      });
      setTimeout(async () => {
        getData()
      }, 1000)
    }
  } else {
    uni.showToast({
      duration: 2000,
      icon: 'none',
      title: '抢单失败'
    });
  }
}

// 开始处理任务
const CommitTaskBeginRecord = async(item)=>{
  const req = {
    c_done_file_id: Guid.NewGuid().ToString(),
    c_done_record: '开始处理任务',
    c_dt: dayjs(new Date(), 'YYYY-MM-DD HH:mm:ss'),
    c_progress: 1,
    c_task_code: getTaskId(item),
    c_total_time: 1,
    c_undone_file_id: Guid.NewGuid().ToString(),
    c_undone_record: ''
  }
  uni.showLoading({ title: "处理中...", mask: true });
  const res = await mainService.request('tasktodo', 'CommitTaskComplateRecord', req);
  uni.hideLoading();
  uni.showToast({
    duration: 2000,
    icon: 'none',
    title: '处理成功'
  });
  setTimeout(async () => {
    getData()
  }, 1000)
}

//置顶
const TopTask = async () => {
  uni.showLoading({ title: "处理中...", mask: true });
  let taskId = getTaskId(currentItem.value.item);
  const req = [taskId];
  const res = await mainService.request('taskallot', 'TopTask', req);
  uni.hideLoading();
  uni.showToast({
    duration: 2000,
    icon: 'none',
    title: '置顶成功'
  });
  setTimeout(async () => {
    getData()
  }, 1000)
}

//作废
const CancelTask = async () => {
  uni.showLoading({ title: "处理中...", mask: true });
  let taskId = getTaskId(currentItem.value.item);
  const req = [taskId];
  const res = await mainService.request('taskallot', 'CancelTask', req);
  uni.hideLoading();
  if (res && res.length > 0) {
    if (res[0].ErrorMsg) {
      uni.showToast({
        duration: 2000,
        icon: 'none',
        title: res[0].ErrorMsg
      });
    } else {
      uni.showToast({
        duration: 2000,
        icon: 'none',
        title: '作废成功'
      });
      setTimeout(async () => {
        getData()
      }, 1000)
    }
  } else {
    uni.showToast({
      duration: 2000,
      icon: 'none',
      title: '作废失败'
    });
  }
}

// 派工/转单
const showAdjustPopup = async (type, item) => {
  formatData.value = {
    title: `${type === '指派' ? '派工' : '转单'}给指定人员`,
    btnTitle: type,
    personName: '', // 处理人
    personId: '',
    costTime: item.c_time + '',
    startTime: item.c_plan_begin_time,
    endTime: item.c_require_complete_time,
  }
  popupAdjust.value.open('center');
}
const hideAdjustPopup = () => {
  popupAdjust.value.close()
}

const judgeAdjust = async () => {
  if (!formatData.value.personId) return;
  let { type } = currentItem.value;
  if (type === '指派') {
    await AssignTask()
  } else if (type === '转单') {
    await TaskDeliverTo()
  }
}

// 指派
const AssignTask = async () => {
  uni.showLoading({ title: "处理中...", mask: true });
  let taskId = getTaskId(currentItem.value.item);
  const req = [{
    TaskId: taskId,
    TaskUserNo: formatData.value.personId  //选择的人员编码
  }];
  const res = await mainService.request('taskallot', 'AssignTask', req);
  uni.hideLoading();
  if (res && res.length > 0) {
    if (res[0].ErrorMsg) {
      uni.showToast({
        duration: 2000,
        icon: 'none',
        title: res[0].ErrorMsg
      });
    } else {
      uni.showToast({
        duration: 2000,
        icon: 'none',
        title: '指派成功'
      });
      closeAllPopup();
      formatData.value.personId = '';
      setTimeout(async () => {
        getData()
      }, 1000)
    }
  } else {
    uni.showToast({
      duration: 2000,
      icon: 'none',
      title: '指派失败'
    });
  }
}

// 转单
const TaskDeliverTo = async () => {
  uni.showLoading({ title: "处理中...", mask: true });
  let taskId = getTaskId(currentItem.value.item);
  const req = {
    TaskId: taskId,
    TaskRecvUserNo: formatData.value.personId  //选择的人员编码
  };
  const res = await rdsRequest(rdsUrl.mainApi, 'tasktodo', 'TaskDeliverTo', req);
  uni.hideLoading();
  uni.showToast({
    duration: 2000,
    icon: 'none',
    title: '转单成功'
  });
  closeAllPopup();
  formatData.value.personId = '';
  setTimeout(async () => {
    getData()
  }, 1000)
}

// 选择人员
const choosePerson = ()=>{
  let data = currentItem.value;
  const taskId = getTaskId(data.item);
  const selectType = data.type;
  uni.navigateTo({
    url: `../../RdsViews/TaskWork/modals/taskSlgSelUser?taskId=${taskId}&selectType=${selectType}`
  });
}
//下拉新增任务-任务类型点击事件
const addTaskItemClick = (item)=>{
  uni.navigateTo({
    url: `../../RdsViews/TaskWork/createTask?menuTitle=${item.c_menu_title}&classCode=${item.c_menu_code}`
  });
  closeAllPopup();
}
//下拉新增任务-更多功能点击事件
const moreTaskItemClick = (item)=>{
  closeAllPopup();
  if(item.c_menu_title==="加入群组"){
    uni.navigateTo({
      url: `../../RdsViews/TaskWork/joinGroup`
    });
  } else if (item.c_menu_title==="任务设置") {
    uni.navigateTo({
      url: `../../RdsViews/TaskWork/setting/main`
    });
  }
}
const SelectionChanged = (selectType,item) => {
  formatData.value.personName = item.Value;
  formatData.value.personId = item.Key;
}

defineExpose({
  SelectionChanged,
  getData,
})

// 关闭更多按钮的弹框
const closeMoreModal = () => {
  if (curTaskList.value.length > 0) {
    curTaskList.value = curTaskList.value.map(x => {
      x.shouMore = false;
      return {
        ...x
      }
    })
  }
}

// 关闭所有弹框
const closeAllPopup = () => {
  hideAdjustPopup(); // 分配弹框
  showFilter.value = false; // 筛选弹框
  showAddTask.value = false; // 新增弹框
}

</script>

<style lang="scss" scoped>
@import '@/main.scss';
@import '../../../static/font/enjoyicon5.0/iconfont.css';

.main-box {
  height: calc(100vh - 50px);
}

.top-view {
  display: flex;
  width: 100%;
  height: 88rpx;
  justify-content: center;
  align-items: center;
  position: relative;

  .status-view {
    position: absolute;
    left: 28rpx;
  }

  .menu-view {
    position: absolute;
    right: 28rpx;
    display: flex;
    justify-content: space-between;
  }
}

.nva-bar {
  font-style: normal;
  font-family: $uni-font-family;
  font-weight: $uni-font-weight-level3;
  color: $uni-text-color-inverse;
  font-size: $uni-font-size-level0;
  line-height: 50rpx;
}

.main-view {
  width: 100%;
  margin-top: 30rpx;
  position: relative;
}

// 筛选框
.popup-content {
  width: 100%;
  display: flex;
  flex-direction: column;
  position: absolute;
  top: 0;
  bottom: -15px;
  left: 0;
  right: 0;
}

.popup-top {
  width: 100%;
  height: auto;
  background: #FFFFFF;

  .btn-view {
    width: 100%;
    height: 100rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-direction: row;
    box-sizing: border-box;
    padding: 0 8rpx;
  }
}

.popup-mask {
  flex: 1;
  background: rgba(0, 0, 0, 0.4);
}

// 空白页
.white-view {
  width: calc(100% - 40rpx);
  height: calc(100% - 20rpx);
  display: flex;
  background: $uni-bg-color-inverse;
  border-radius: 20rpx;
  margin: 0 20rpx 20rpx 20rpx;
  flex-direction: column;
  align-items: center;
  font-family: $uni-font-family;
  font-weight: $uni-font-weight-level1;
  font-size: $uni-font-size-level3;
  color: $uni-text-color-hint;
  line-height: 40rpx;
  font-style: normal;
}

.tips-level1 {
  font-size: $uni-font-size-level0;
  color: $uni-text-color-primary;
  line-height: 50rpx;
}

.tips-level2 {
  margin-top: 20rpx;
  margin-bottom: 40rpx;
}

// 派单框
.popup-adjust {
  width: 630rpx;
  height: 645rpx;
}

// 延期弹框
.popup-delay {
  width: 630rpx;
  height: 902rpx;
}
</style>
